﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.Odbc;
using System.Collections;

namespace MPPIT
{
    public partial class MainForm : Form
    {
        bool m_closeForm = false;
        string m_connectionFile = "connection.ini";
        string m_configFile = "config.ini";
        string m_scheduleFile = "schedule.ini";
        string m_machineFile = "machine.ini";
        string m_connectionString = "";

        public MainForm()
        {
            InitializeComponent();
            
        }

        private void setEnableButtonOKApply(Control maincontrol)
        {
            foreach (Control ctrl in maincontrol.Controls)
            {
                if (ctrl is TextBox)
                {
                    ctrl.TextChanged += new EventHandler(ctrl_TextChanged);
                }
                if (ctrl is CheckBox)
                {
                    CheckBox chb = (CheckBox)ctrl;
                    chb.CheckedChanged += new EventHandler(ctrl_TextChanged);
                }
                setEnableButtonOKApply(ctrl);
            }
        }

        void ctrl_TextChanged(object sender, EventArgs e)
        {
            buttonApply.Enabled = true;
            buttonOK.Enabled = true;
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Show();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!m_closeForm)
            {
                e.Cancel = true;
                hideFormShowNotofication();
            }
        }

        private void hideFormShowNotofication()
        {
            Hide();
            notifyIcon.Visible = true;
            notifyIcon.BalloonTipText = "Moobing Premiere Promag Integration Tools is Running";
            notifyIcon.BalloonTipTitle = "MPPIT";
            notifyIcon.ShowBalloonTip(3000);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_closeForm = true;
            Close();
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Show();
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            
            // hideFormShowNotofication();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void buttonPath_Click(object button, EventArgs e)
        {
            Control sender = (Control)button;
            if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (sender.Name == "buttonSourcePath")
                    textBoxSourcePath.Text = folderBrowserDialog.SelectedPath;
                if (sender.Name == "buttonBackupPath1")
                    textBoxBackupPath1.Text = folderBrowserDialog.SelectedPath;
                if (sender.Name == "buttonBackupPath2")
                    textBoxBackupPath2.Text = folderBrowserDialog.SelectedPath;
                if (sender.Name == "buttonBackupPath3")
                    textBoxBackupPath3.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void textBoxCardID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar >= '0' && e.KeyChar <= '9'  || e.KeyChar == '\b') //The  character represents a backspace
            {
                e.Handled = false; //Do not reject the input
            }
            else
            {
                e.Handled = true; //Reject the input
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            loadConnection();
            loadConfiguration();
            loadSchedule();
            loadMachine();
            setEnableButtonOKApply(this);
        }

        private void loadSchedule()
        {
            listViewScedule.Items.Clear();
            if (!File.Exists(m_scheduleFile))
                File.Create(m_scheduleFile);
            StreamReader rd = new StreamReader(m_scheduleFile);
            int count = 0;
            ListViewItem item = null;
            while (!rd.EndOfStream)
            {
                if ((count % 3) == 0)
                {
                    item = new ListViewItem();
                    listViewScedule.Items.Add(item);
                }
                string line = rd.ReadLine();
                string[] words = line.Split('=');
                switch (words[0].ToUpper())
                {
                    case "NAME":
                        item.Text = words[1]; break;
                    case "TIME":
                        item.SubItems.Add(words[1]); break;
                    case "ENABLE":
                         bool dt= false;
                        bool.TryParse(words[1], out dt); 
                        item.SubItems.Add(dt?"Ready":"Disable"); break;
                }
                count++;
            }
            rd.Close();
        }

        private void loadMachine()
        {
            listViewMachine.Items.Clear();
            if (!File.Exists(m_machineFile))
                File.Create(m_machineFile);
            StreamReader rd = new StreamReader(m_machineFile);
            ListViewItem item = null;
            while (!rd.EndOfStream)
            {
                item = new ListViewItem();
                listViewMachine.Items.Add(item);
                string line = rd.ReadLine();
                string[] words = line.Split('=');
                item.Text = words[0];
                item.SubItems.Add(words[1]);
            }
            rd.Close();
        }

        private void loadConfiguration()
        {
            if (!File.Exists(m_configFile))
                File.Create(m_configFile);
            StreamReader rd = new StreamReader(m_configFile);
            while (!rd.EndOfStream)
            {
                string line = rd.ReadLine();
                string[] words = line.Split('=');
                switch (words[0].ToUpper())
                {
                    case "CARDID":
                        textBoxCardID.Text = words[1]; break;
                    case "IO":
                        bool dt= false;
                        bool.TryParse(words[1], out dt); 
                            checkBoxDetermine.Checked =dt; 
                        break;
                    case "SOURCEPATH":
                        textBoxSourcePath.Text = words[1]; break;
                    case "BACKUPPATH1":
                        textBoxBackupPath1.Text = words[1]; break;
                    case "BACKUPPATH2":
                        textBoxBackupPath2.Text = words[1]; break;
                    case "BACKUPPATH3":
                        textBoxBackupPath3.Text = words[1]; break;
                    case "SOURCEEXT":
                        textBoxSourceExtension.Text = words[1]; break;
                    case "BACKUPEXT":
                        textBoxBackupExtension.Text = words[1]; break;
                }
            }
            rd.Close();
        }
        private void saveConfiguration()
        {
            if (File.Exists(m_configFile))
                File.Delete(m_configFile);
            else
                File.Create(m_configFile);
            StreamWriter rd = new StreamWriter(m_configFile);
            rd.WriteLine("CARDID=" + textBoxCardID.Text);
            rd.WriteLine("IO=" + checkBoxDetermine.Checked.ToString());
            rd.WriteLine("SOURCEPATH=" + textBoxSourcePath.Text);
            rd.WriteLine("BACKUPPATH1=" + textBoxBackupPath1.Text);
            rd.WriteLine("BACKUPPATH2=" + textBoxBackupPath2.Text);
            rd.WriteLine("BACKUPPATH3=" + textBoxBackupPath3.Text);
            rd.WriteLine("SOURCEEXT=" + textBoxSourceExtension.Text);
            rd.WriteLine("BACKUPEXT=" + textBoxBackupExtension.Text);
            rd.Close();
        }

        private void loadConnection()
        {
            m_connectionString = "";
            if (!File.Exists(m_connectionFile))
                File.Create(m_connectionFile);
            StreamReader rd = new StreamReader(m_connectionFile);
            while (!rd.EndOfStream)
            {
                string line = rd.ReadLine();
                string[] words = line.Split('=');
                switch (words[0].ToUpper())
                {
                    case "DSN":
                        textBoxDSN.Text = words[1];break;
                    case "UID":
                        textBoxUserID.Text = words[1];break;
                    case "PWD":
                        textBoxPassword.Text = words[1];break;
                }
                m_connectionString += ";" + line;
            }
            rd.Close();
        }
        private void saveConnection()
        {
            if (File.Exists(m_connectionFile))
                File.Delete(m_connectionFile);
            else
                File.Create(m_connectionFile);
            StreamWriter rd = new StreamWriter(m_connectionFile);
            rd.WriteLine("DSN=" + textBoxDSN.Text.Trim());
            rd.WriteLine("UID=" + textBoxUserID.Text.Trim());
            rd.WriteLine("PWD=" + textBoxPassword.Text.Trim());
            rd.Close();
            m_connectionString = "DSN=" + textBoxDSN.Text.Trim() + ";UID=" + textBoxUserID.Text.Trim() + ";PWD=" + textBoxPassword.Text.Trim();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            saveConnection();
            saveConfiguration();
            saveSchedule();
            saveMachine();
            Close();
        }

        private void saveSchedule()
        {
            if (File.Exists(m_scheduleFile))
                File.Delete(m_scheduleFile);
            else
                File.Create(m_scheduleFile);
            StreamWriter rd = new StreamWriter(m_scheduleFile);
            foreach (ListViewItem itm in listViewScedule.Items)
            {
                rd.WriteLine("NAME=" + itm.Text);
                rd.WriteLine("TIME=" + itm.SubItems[1].Text);
                rd.WriteLine("ENABLE=" + (itm.SubItems[2].Text == "Ready" ? "True" : "False"));
            }
            rd.Close();
        }

        private void saveMachine()
        {
            if (File.Exists(m_machineFile))
                File.Delete(m_machineFile);
            else
                File.Create(m_machineFile);
            StreamWriter rd = new StreamWriter(m_machineFile);
            foreach (ListViewItem itm in listViewMachine.Items)
            {
                rd.WriteLine(itm.Text + "=" + itm.SubItems[1].Text);
            }
            rd.Close();
        }

        private void buttonTestConnection_Click(object sender, EventArgs e)
        {
            OdbcConnection conenction = new OdbcConnection();
            m_connectionString = "DSN=" + textBoxDSN.Text.Trim() + ";UID=" + textBoxUserID.Text.Trim() + ";PWD=" + textBoxPassword.Text.Trim() + ";";
            conenction.ConnectionString = m_connectionString;
            try
            {
                conenction.Open();
                MessageBox.Show("Connection is successfuly", "Connection Test", MessageBoxButtons.OK);
                conenction.Close();
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Connection Test", MessageBoxButtons.OK);
            }
            finally
            {
                conenction.Dispose();
            }
        }

        private void createScheduleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ScheduleForm frm = new ScheduleForm();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ListViewItem itm = listViewScedule.Items.Add(frm.ScheduleName);
                itm.SubItems.Add(frm.Time);
                itm.SubItems.Add(frm.EnableStatus ? "Ready" : "Disabled");
            }
            ctrl_TextChanged(sender, e);
        }

        private void createMachineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MachineForm frm = new MachineForm();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ListViewItem itm = listViewMachine.Items.Add(frm.Code);
                itm.SubItems.Add(frm.IN ? "IN" : "OUT");
            }
            ctrl_TextChanged(sender, e);
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            openToolStripMenuItem.Enabled = listViewScedule.SelectedItems.Count > 0;
            deleteScheduleToolStripMenuItem.Enabled = listViewScedule.SelectedItems.Count > 0;
        }

        private void listViewMachine_SelectedIndexChanged(object sender, EventArgs e)
        {
            openToolStripMenuItemMachine.Enabled = listViewMachine.SelectedItems.Count > 0;
            deleteToolStripMenuItemMachine.Enabled = listViewMachine.SelectedItems.Count > 0;
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ScheduleForm frm = new ScheduleForm();
            frm.ScheduleName = listViewScedule.SelectedItems[0].Text;
            frm.Time = listViewScedule.SelectedItems[0].SubItems[1].Text;
            frm.EnableStatus = listViewScedule.SelectedItems[0].SubItems[2].Text == "Ready";
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                listViewScedule.SelectedItems[0].Text = frm.ScheduleName;
                listViewScedule.SelectedItems[0].SubItems[1].Text = frm.Time;
                listViewScedule.SelectedItems[0].SubItems[2].Text = frm.EnableStatus ? "Ready" : "Disabled";
            }
        }

        private void openToolStripMenuItemMachine_Click(object sender, EventArgs e)
        {
            MachineForm frm = new MachineForm();
            frm.Code = listViewMachine.SelectedItems[0].Text;
            frm.IN = listViewMachine.SelectedItems[0].SubItems[1].Text == "IN";
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                listViewMachine.SelectedItems[0].Text = frm.Code;
                listViewMachine.SelectedItems[0].SubItems[1].Text = frm.IN ? "IN" : "OUT";
            }
        }

        private void deleteScheduleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listViewScedule.SelectedItems[0].Remove();
            ctrl_TextChanged(sender, e);
        }

        private void deleteToolStripMenuItemMachine_Click(object sender, EventArgs e)
        {
            listViewMachine.SelectedItems[0].Remove();
            ctrl_TextChanged(sender, e);
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listViewScedule.Items.Clear();
            loadSchedule();
        }

        private void refreshToolStripMenuItemMachine_Click(object sender, EventArgs e)
        {
            listViewMachine.Items.Clear();
            loadMachine();
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            openToolStripMenuItem_Click(sender, e);
            ctrl_TextChanged(sender, e);
        }

        private void listViewMachine_DoubleClick(object sender, EventArgs e)
        {
            openToolStripMenuItemMachine_Click(sender, e);
            ctrl_TextChanged(sender, e);
        }

        private void buttonApply_Click(object sender, EventArgs e)
        {
            saveConfiguration();
            saveConnection();
            saveSchedule();
            saveMachine();
            buttonOK.Enabled = false;
            buttonApply.Enabled = false;
        }
        
        private void MainForm_VisibleChanged(object sender, EventArgs e)
        {
            if (Visible)
            {
                loadConfiguration();
                loadConnection();
                loadSchedule();
                loadMachine();
                buttonOK.Enabled = false;
                buttonApply.Enabled = false;
            }
        }

        private void buttonExecuteNow_Click(object sender, EventArgs e)
        {
            Execute();
        }

        private void Execute()
        {
            string sourceFolder = textBoxSourcePath.Text.Trim();
            string sourceExt = textBoxSourceExtension.Text.Trim();
            string backupFolder1 = textBoxBackupPath1.Text.Trim();
            string backupFolder2 = textBoxBackupPath2.Text.Trim();
            string backupFolder3 = textBoxBackupPath3.Text.Trim();
            string backupExt = textBoxBackupExtension.Text.Trim();

            int cardDeflen = 14;
            int.TryParse(textBoxCardID.Text, out cardDeflen);
            int cardlen = cardDeflen;

            if (!Directory.Exists(backupFolder1))
                Directory.CreateDirectory(backupFolder1);
            if (!Directory.Exists(backupFolder2))
                Directory.CreateDirectory(backupFolder2);
            if (!Directory.Exists(backupFolder3))
                Directory.CreateDirectory(backupFolder3);

            string[] files = System.IO.Directory.GetFiles(sourceFolder);
            IList result = new ArrayList();
            IList errorMessage = new ArrayList();
            int ln = 0;
            foreach (string file in files)
            {
                string ext = Path.GetExtension(file);
                if (ext.ToLower() != "." + sourceExt.ToLower()) continue;
                StreamReader sr = new StreamReader(file);
                while (!sr.EndOfStream)
                {
                    ln++;
                    try
                    {
                        //003[0],00000002227959[1],0[2],2014/03/27[3],11:15:39[4]
                        string line = sr.ReadLine();
                        string[] words = line.Split(',');
                        DateTime date = Convert.ToDateTime(words[3] + " " + words[4]);
                        string cardID = words[1];

                        cardID = cardID.Length > cardlen ? cardID.Substring(cardID.Length - cardlen, cardlen) : cardID;
                        Timesheet ts = new Timesheet(words[0], words[1], words[2], date, date);
                        result.Add(ts);
                    }
                    catch (Exception x)
                    {
                        errorMessage.Add("Error reading file " + file + " at line " + ln + " : " + x.Message);
                    }
                }
                sr.Close();
                if (errorMessage.Count > 0)
                {
                    writeLog(file + ".log", errorMessage);
                }
                else
                {
                    if (File.Exists(file + ".log"))
                        File.Delete(file + ".log");

                    bool inserted = executeToDB(result);

                    if (inserted)
                    {
                        if (!(File.Exists(backupFolder1 + @"\" + Path.GetFileNameWithoutExtension(file) + "." + backupExt)))
                            File.Copy(file, backupFolder1 + @"\" + Path.GetFileNameWithoutExtension(file) + "." + backupExt);
                        if (!(File.Exists(backupFolder2 + @"\" + Path.GetFileNameWithoutExtension(file) + "." + backupExt)))
                            File.Copy(file, backupFolder2 + @"\" + Path.GetFileNameWithoutExtension(file) + "." + backupExt);
                        if (!(File.Exists(backupFolder3 + @"\" + Path.GetFileNameWithoutExtension(file) + "." + backupExt)))
                            File.Copy(file, backupFolder3 + @"\" + Path.GetFileNameWithoutExtension(file) + "." + backupExt);
                        File.Delete(file);
                    }
                    else
                        writeLog(file + ".log", new string[] { "Error while inserting to DB" });
                }

            }
        }

        private bool executeToDB(IList result)
        {

            return false;
        }
        private void writeLog(string filename, IList message)
        {
            if(File.Exists(filename))
                File.Delete(filename);
            StreamWriter ew = new StreamWriter(filename);
            foreach(string msg in message)
                ew.WriteLine(msg);
            ew.Close();
        }

        private void checkBoxDetermine_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxDetermine.Checked)
            {
                if (!tabControl1.TabPages.Contains(tabPageMachineID))
                    tabControl1.TabPages.Add(tabPageMachineID);
            }
            else
                tabControl1.TabPages.Remove(tabPageMachineID);
        }
    }
    
    public class Timesheet
    {
        public string MACHINE_NUMBER = "";
        public string CARD_ID = "";
        public string EVENT_IO = "";
        public DateTime DATE = new DateTime(2000, 1, 1);
        public DateTime TIME = new DateTime(2000, 1, 1);
        public Timesheet(string mcnumber, string cardid, string eventIO, DateTime date, DateTime time)
        {
            MACHINE_NUMBER = mcnumber;
            CARD_ID = cardid;
            EVENT_IO = eventIO;
            DATE = date.Date;
            TIME = time;
        }
    }
}
